package dou.net.protocol;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 协议对象基类
 * @author wizardc
 */
public abstract class AbstractProtocol implements IProtocol
{
    /**
     * 消息 ID 列表
     */
    protected List<Integer> _msgIDList;

    /**
     * 消息处理表
     */
    protected Map<Integer, Class<? extends IMessageHandler>> _messageHandlerMap;

    /**
     * 构造函数
     * @param id 协议 ID
     */
    public AbstractProtocol()
    {
        _msgIDList = new ArrayList<>();
        _messageHandlerMap = new ConcurrentHashMap<>();
        this.initMessageHandlers();
    }

    @Override
    public List<Integer> msgIDList() {
        return _msgIDList;
    }

    /**
     * 初始化所有消息处理对象
     */
    protected abstract void initMessageHandlers();

    @Override
    public void registerMessageHandler(int msgID, Class<? extends IMessageHandler> messageHandlerClass) throws Exception
    {
        if(_messageHandlerMap.containsKey(msgID))
        {
            throw new Exception("This msgID already exists!");
        }
        if(messageHandlerClass == null)
        {
            throw new Exception("This messageHandlerClass can not be null!");
        }
        _msgIDList.add(msgID);
        _messageHandlerMap.put(msgID, messageHandlerClass);
    }

    @Override
    public IMessageHandler getMessageHandler(int msgID) throws IllegalAccessException, InstantiationException
    {
        if(_messageHandlerMap.containsKey(msgID))
        {
            Class<? extends IMessageHandler> messageHandlerClass = _messageHandlerMap.get(msgID);
            return messageHandlerClass.newInstance();
        }
        return null;
    }

    @Override
    public abstract void cleanup();
}
